package com.jfinal.weixin.controller;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.weixin.model.TreeHoleArticle;
import com.jfinal.weixin.model.TreeHoleComment;
import com.jfinal.weixin.sdk.utils.StringUtil;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by gongi on 16/6/12.
 */
public class TreeHoleController extends Controller {
    /**
     * 显示列表,进入主页
     */
    public void index() {
        render("/treehole/treehole.html");
    }

    /**
     * 保存主题
     */
    public void saveArticle() {
        String nowtime = StringUtil.getCurTime();
        String content = getPara("text", "");
        int userid = getParaToInt("userid", 0);
        TreeHoleArticle treeHoleArticle = new TreeHoleArticle();
        treeHoleArticle.set("openid", userid);
        treeHoleArticle.set("content", content);
        treeHoleArticle.set("time", nowtime);
        boolean flag = treeHoleArticle.save();
        renderText(flag + "");
    }

    public void saveComment() {
        String nowtime = StringUtil.getCurTime();
        String content = getPara("text", "");
        int articleid = getParaToInt("articleid", 0);
        TreeHoleComment treeHoleComment = new TreeHoleComment();
        treeHoleComment.set("openid", "a");
        treeHoleComment.set("content", content);
        treeHoleComment.set("time", nowtime);
        treeHoleComment.set("articleid", articleid);
        boolean flag = treeHoleComment.save();
        renderText(flag + "");
    }

    /**
     * 获取主题列表
     *
     * @return
     */
    public void getList() {
        int pageNumber = getParaToInt("page", 1);
        String sql = "from treehole_article where 1=1";
        Page<Record> userPage;
        userPage = Db.paginate(pageNumber, 10, "select *", sql);
        renderJson(userPage);
    }

    public void article() {
        int articleId = getParaToInt("articleid", 1);
        TreeHoleArticle treeHoleArticle = TreeHoleArticle.dao.getArticleById(articleId);
        List<TreeHoleComment> treeHoleCommentList = TreeHoleComment.dao.getCommentByArticleId(articleId);
        setAttr("treeHoleCommentList",treeHoleCommentList);
        setAttr("treeHoleArticle",treeHoleArticle);
        render("/treehole/article.html");
    }


}
